/*
 * Copyright (c) 2025 EasyAdmin
 * All rights reserved.
 *
 * This file is part of the [EasAdmin] project.
 * Unauthorized copying of this file, via any medium, is strictly prohibited.
 * Proprietary and confidential.
 *
 * Author: EasyAdmin ( 1073602@qq.com )
 * Website: https://www.xhxiao.com
 */
package com.easy.module.system.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.framework.common.utils.AssertUtil;
import com.easy.module.system.entity.SysTemplate;
import com.easy.module.system.mapper.SysTemplateMapper;
import com.easy.module.system.service.ISysTemplateService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * 模板信息 Service业务
 *
 * @author EasyAdmin ( 1073602@qq.com )
 * @date 2025-08-17 16:37:54
 */
@RequiredArgsConstructor
@Service
public class SysTemplateServiceImpl extends ServiceImpl<SysTemplateMapper, SysTemplate> implements ISysTemplateService {


    final Configuration freeMarkerConfig;

    @SneakyThrows
    @Override
    public String generateTemplate(String content, Map<String, Object> variables) {
        Template template = new Template("temp", new StringReader(content), freeMarkerConfig);
        try (StringWriter writer = new StringWriter()) {
            template.process(variables, writer);
            return writer.toString();
        }
    }


    @Override
    public String generateTemplate(Long templateId, Map<String, Object> variables) {
        SysTemplate sysTemplate = getById(templateId);
        AssertUtil.isNotEmpty(sysTemplate, "模板不存在");
        return generateTemplate(sysTemplate.getContent(), variables);
    }

    @Override
    public SysTemplate getByTemplateCode(String templateCode) {
        return getOne(lambdaQueryWrapper().eq(SysTemplate::getCode, templateCode));
    }

}
